package org.siam.impl.data.formatting.formatters {
	
	import mx.formatters.NumberFormatter;
	
	import org.siam.core.data.formatting.IFormatter;
	import org.siam.utils.RuntimeError;
	import org.siam.utils.StringUtils;
	
	public class NumberFormatter extends mx.formatters.NumberFormatter implements IFormatter {
		
		private static const VALID_REGEXP:RegExp = /(-?)#([,.]?)###([,.]?)(#*)([+-~]?)/;
		
		private var _formatString:String;
		
		public function NumberFormatter() {
		}
		
		public function get formatString():String {
			return _formatString;
		}
		
		public function set formatString(value:String):void {
			if (value == _formatString)
				return;
				
			parseFormatString(value);
			_formatString = value;
		}
		
		private function parseFormatString(value:String):void{
			var decimalSeparatorTo:String = null;
			var precision:Object = null;
			var rounding:String = null;
			var thousandsSeparatorTo:String = null;
			var useNegativeSign:Object = null;
			var useThousandsSeparator:Object = null;
			
			if (value) {
				var results:Array = value.match(VALID_REGEXP);
				if (!results) {
					throw new RuntimeError("Incompatible formatString: '%s'", value);
				}
				useNegativeSign = results[1] == "-";
				useThousandsSeparator = !StringUtils.isEmpty(results[2]);
				if (useThousandsSeparator)
					thousandsSeparatorTo = results[2];
				if (!StringUtils.isEmpty(results[3]))
					decimalSeparatorTo = results[3];
				precision = results[4].length;
				switch (results[5]) {
					case "+": rounding = "up"; break;
					case "-": rounding = "down"; break;
					case "~": rounding = "nearest"; break;
				}
			}
			
			super.decimalSeparatorTo = super.decimalSeparatorFrom = decimalSeparatorTo;
			super.precision = precision;
			super.rounding = rounding;
			super.thousandsSeparatorTo = super.thousandsSeparatorFrom = thousandsSeparatorTo;
			super.useNegativeSign = useNegativeSign;
			super.useThousandsSeparator = useThousandsSeparator;
		}		
	}
}